package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 *
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    //线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct//当前类初始化完毕后执行线程池
    private void init(){
        //提交任务
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    //TODO 压测
    private class VoucherOrderHandler implements Runnable {

        String queueName = "stream.orders";
        @Override
        public void run() {
            while (true) {
                try {
                    //不断从消息队列中取出订单 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream,orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed()));
                    //判断消息是否获取成功
                    if (list == null || list.isEmpty()) {
                        //如果失败，说明没有消息，继续下一次循环
                        continue;
                    }

                    //解析消息中的订单消息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    //获取成功，可以下单
                    handleVoucherOrder(voucherOrder);
                    //ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                    //创建订单

                } catch (Exception e) {
                    log.error("处理订单异常",e);
                    //消息抛异常，没有被ACK确认，会进入pendinglist
                    handlePendingList();
                }
            }

        }

        private void handlePendingList() {
            while (true) {
                try {
                    //不断从pending-list队列中取出订单 XREADGROUP GROUP g1 c1COUNT 1  STREAMS stream,orders 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0")));
                    //判断消息是否获取成功
                    if (list == null || list.isEmpty()) {
                        //如果失败，说明pending-list没有消息，结束循环
                        break;
                    }

                    //解析消息中的订单消息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    //获取成功，可以下单
                    handleVoucherOrder(voucherOrder);
                    //ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                    //创建订单

                } catch (Exception e) {
                    log.error("处理pending-list订单异常",e);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }

                }
            }
        }
    }

    /*//阻塞队列
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);
    //线程任务,内部类
    private class VoucherOrderHandler implements Runnable{

        @Override
        public void run() {
        while(true){
            //不断从阻塞队列中取出订单
            try {
                VoucherOrder voucherOrder = orderTasks.take();//不占用cpu,阻塞获取
                //创建订单
                handleVoucherOrder(voucherOrder);
            } catch (Exception e) {
                log.error("处理订单异常");
            }
            }

        }
    }*/

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        //获取用户id
        Long userId = voucherOrder.getUserId();
        //创建锁对象
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //获取锁
        //TODO JMeter测试
        boolean isLock = lock.tryLock();//默认不等待，锁超时30秒释放
        //判断释放获取锁成功
        if(!isLock){
            //获取锁失败，返回错误信息或重试
            log.error("不允许重复下单");
            return;
        }
        try {
            //这里子线程无法获取threadlocal的代理对象（事务），需在外面获取
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
             proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    //加载脚本
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private IVoucherOrderService proxy;

    //基于阻塞队列的异步秒杀存在：内存限制，数据安全问题
    //基于redis的stream结构作为消息队列，实现异步秒杀下单
    //创建一个stream类型的消息队列，名为stream.orders
    //修改之前的秒杀下单lua脚本，在认定有抢购资格后，直接向stream.orders中添加消息，内容包含voucherid,userid,orderid
    //项目启动时开启一个线程任务，尝试获取stream.orders中的消息，完成下单

    //TODO 压测
    @Override
    public Result seckillVoucher(Long voucherId) {
        //获取用户
        Long userId = UserHolder.getUser().getId();
        //订单id
        long orderId = redisIdWorker.nextId("order");
        //执行lua脚本，完成秒杀资格的判断
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(), voucherId.toString(), userId.toString(),String.valueOf(orderId));
        //判断结果是否为0
        int r = result.intValue();
        if (r!=0){
            //不为0，代表没有资格
            return Result.fail(r==1?"库存不足":"不能重复下单");
        }


        //获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        //返回订单id
        return Result.ok(orderId);
    }


//    改进秒杀业务，提高并发性能,变同步下单为异步下单
//    新增秒杀优惠券的同时，将优惠券信息保存到redis中
//    基于lua脚本，通过redis判断秒杀库存，一人一单，决定用户是否抢购成功
//    如果抢购成功，将优惠券id和用户id封装后存入阻塞队列
//    开启线程任务，不断从阻塞队列中获取信息，实现异步下单功能

    /*//TODO 压测
    @Override
    public Result seckillVoucher(Long voucherId) {
        //获取用户
        Long userId = UserHolder.getUser().getId();
        //执行lua脚本，完成秒杀资格的判断
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString());
        //判断结果是否为0
        int r = result.intValue();
        if (r!=0){
            //不为0，代表没有资格
            return Result.fail(r==1?"库存不足":"不能重复下单");
        }

        //为0，有购买资格，不是直接下单，把下单信息创建，保存到阻塞队列，执行异步下单
        //创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        //用户id
        voucherOrder.setUserId(userId);
        //代金券id
        voucherOrder.setVoucherId(voucherId);
        //放入阻塞队列
        orderTasks.add(voucherOrder);

        //获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        //返回订单id
        return Result.ok(orderId);
    }*/

/*    @Override
    public Result seckillVoucher(Long voucherId) {

        //查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);

        //判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())){//开始时间是当前时间之后
            return Result.fail("秒杀尚未开始");
        }
        //判断是否结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())){//结束时间是当前时间之前
            return Result.fail("秒杀已结束");
        }
        //判断库存是否充足
        if (voucher.getStock()<1) {
            //库存不足
            return Result.fail("库存不足");
        }

        //订单新增+库存扣减
        Long userId = UserHolder.getUser().getId();

//        //单机版：加锁，防止并发，线程交叉而导致一人多单,但在集群下锁会失效，
//        //锁住id,减小锁的粒度，toString()会创建新对象，会导致同一用户会有多把锁，intern()会返回已有对象
//       synchronized(userId.toString().intern()) {
//            //先提交事务再释放锁
//
//            //非事务对象调用事务方法，事务会失效，事务由spring动态代理的对象调用，
//            // 而这里的this不是代理对象，因此需拿到代理对象
//            //return this.createVoucherOrder(voucherId);
//
//            //通过AopContext拿到对应接口的代理对象，同时引入aspectjweaver依赖，注意启动类要暴露代理对象，默认不暴露@EnableAspectJAutoProxy(exposeProxy = true)
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        }

        //集群版,分布式锁
        //创建redis分布式锁对象,自定义  问题：不可重入，不可重试，超时就释放，主从一致性
       // SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
        //创建锁对象,redisson
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //获取锁
        //TODO JMeter测试
        boolean isLock = lock.tryLock();//默认不等待，锁超时30秒释放
        //判断释放获取锁成功
        if(!isLock){
            //获取锁失败，返回错误信息或重试
            return Result.fail("不允许重复下单");
        }
        try {
            //获取代理对象
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            lock.unlock();
        }
    }*/

    //订单新增+库存扣减

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
//        //一人一单
//        Long userId = UserHolder.getUser().getId();
        //这里是异步，不能通过threadlocal获取
        Long userId = voucherOrder.getUserId();

        //根据用户id和订单id查订单，是否买过
        int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        //判断是否存在
        if (count>0){
            //用户已经购买了
            log.error("不允许重复购买");
            return;
        }

        //扣减库存
        // TODO JMeter测试
        boolean success = seckillVoucherService.update()
                .setSql("stock=stock-1")//set stock =stock -1
                .eq("voucher_id", voucherOrder.getVoucherId())//where id = ?
            //  .eq("stock", voucher.getStock())//and stock = ?       //采用乐观锁解决超卖，用数据本身代替版本号，同时请求失败的要重试
                .gt("stock",0)//and stock > 0   //优化，库存大于零即可扣减
                .update();
        if (!success){
            //扣减失败
            log.error("库存不足");
            return ;
        }
        //创建订单
        //写入数据库
        save(voucherOrder);

//        //返回订单id
//        return Result.ok(orderId);

    }

}
